/**
 * Created by weiwenhai on 2016/8/24.
 * 考生管理  ，服务层
 */
angular.module('App')
  .factory('StuRes', ['$resource', 'EXAM_SERVER', function ($resource, EXAM_SERVER) {
    return $resource(EXAM_SERVER + '/api/student_exam_infos/:student_exam_info_id', {student_exam_info_id: '@stuExamInfoId'}, {
      edit: {method: "PUT"}, query: {isArray: false},
      import: {
        method: 'POST', transformRequest: function (data) {
          var fd = new FormData();
          angular.forEach(data, function (value, key) {
            fd.append(key, value);
          });
          return fd;
        }, headers: {'Content-Type': undefined}, url: EXAM_SERVER + '/import/student_exam_infos'
      },
      ImportPhotos: {
        method: 'POST', transformRequest: function (data) {
          var fd = new FormData();
          angular.forEach(data, function (value, key) {
            fd.append(key, value);
          });
          return fd;
        }, headers: {'Content-Type': undefined}, url: EXAM_SERVER + '/import/student_exam_infos/facepp'
      }
    });
  }])

  //获取多条学生信息记录
  .factory('MultiStu', ['$q', 'StuRes', function ($q, StuRes) {
    //返回一个函数
    return function (params) {
      //创建延迟对象
      var delay = $q.defer();
      //发起请求获取数据
      StuRes.query(params, function (resp) {
        //成功
        delay.resolve(resp);
      }, function (err) {
        //失败
        // delay.reject({'msg':'请求失败'});
        delay.reject(err);
      });
      return delay.promise;
    };
  }])

  //获取单条学习中心
  .factory('StuOne', ['$q', 'StuRes', function ($q, StuRes) {
    //返回一个函数
    return function (params) {
      //创建一个对象
      var delay = $q.defer();
      //发起请求获取数据
      StuRes.get(params, function (resp) {
        //成功
        delay.resolve(resp);
      }, function (err) {
        //拒绝
        // delay.reject({'msg':'请求失败'});
        delay.reject(err);
      });
      return delay.promise;
    };
  }])


  //定义导入指令
  .directive('stuImport', ['StuRes', 'toaster', '$state', function (StuRes, toaster, $state) {
    return {
      restrict: 'A',
      scope: {
        batId: "@stuImport",
        importErr: '=',
        closeModal: '&',
        importing: '='
      },
      link: function ($scope, $element) {
        $element.bind('change', function () {
          // 显示提示语，并禁用取消按钮
          $scope.importing = true;
          if ($element.val().endsWith('.xls') || $element.val().endsWith('.xlsx')) {
            $scope.$apply(function () {
              //toaster.pop("wait", "温馨提示", "正在导入...");
              $scope.$emit('$stateChangeStart');
              $state.go(".", {reload: true});
              var file = $element[0].files[0];
              StuRes.import({stuExamInfoExcelFile: file, onlienBatchId: $scope.batId}, function (resp) {
                // 隐藏提示语，用启用取消按钮
                $scope.importing = false;
                console.log(resp);
                $element.val('');

                $scope.$emit('$stateChangeSuccess');
                toaster.pop("success", "温馨提示", "导入成功");
                $scope.importErr = undefined;
                $scope.closeModal();
              }, function (error) {
                // 隐藏提示语，用启用取消按钮
                $scope.importing = false;
                $element.val('');
                $scope.$emit('$stateChangeError');
                toaster.pop("error", "导入失败", error.data.message);
                //toaster.pop("error", "导入失败");
                //console.log('error is :', error);
                $scope.importErr = error.data;
              });
            });
          } else {
            $scope.$apply(function () {
              $element.val('');
              toaster.pop("error", "错误提示", '只允许上传Excel格式的文件');
              //$state.go(".");
            });
          }
        });
      }
    }
  }])

  //定义导入学生照片指令
  .directive('stuImportPhotos', ['StuRes', 'toaster', '$uibModal', '$state', function (StuRes, toaster, $uibModal, $state) {
    return {
      restrict: 'A',
      link: function ($scope, $element) {
        $element.bind('change', function () {
          console.log("element is", $element);
          if ($element.val().endsWith('.zip')) {
            $scope.$apply(function () {
              toaster.pop("wait", "温馨提示", "正在导入...");
              $scope.$emit('$stateChangeStart');
              $state.go(".", {reload: true});
              var file = $element[0].files[0];

              StuRes.ImportPhotos({file: file}, function (resp) {
                $element.val('');
                console.log('导入考生照片成功，resp is：', resp);
                $scope.$emit('$stateChangeSuccess');
                toaster.pop("success", "温馨提示", "导入成功");
                $state.reload();
              }, function (error) {
                $element.val('');
                console.log('导入考生照片失败，error is：', error);
                $scope.$emit('$stateChangeSuccess');
                toaster.pop("error", "导入失败", error.data.message);

                if (error.data && error.data.length > 0) {
                  // 导入有错误
                  $uibModal.open({
                    animation: true,
                    templateUrl: 'photos.import.error.html',
                    controller: ['$scope', 'errorRows', '$uibModalInstance', function ($scope, errorRows, $uibModalInstance) {
                      $scope.errorRows = errorRows;
                      $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                      };
                    }],
                    resolve: {
                      errorRows: function () {
                        return error.data;
                      }
                    }
                  });
                }

              });

            });
          } else {
            $scope.$apply(function () {
              $element.val('');
              toaster.pop("error", "错误提示", '只允许上传zip格式的文件');
            });
          }

        });
      }
    }
  }]);
